package com.ruoyi.management_controller.userinfo.interceptor;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Component
public class CustomInterceptor implements HandlerInterceptor {



    private static ServerTokenConfig serverTokenConfig;

    @Autowired
    public void init(ServerTokenConfig serverTokenConfig) {
        CustomInterceptor.serverTokenConfig = serverTokenConfig;
    }
    /**
     * 拦截所有请求，验证TOKEN是否有效
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {

            // 做token校验
           // String token = request.getHeader("Authorization");
            String token = request.getHeader("token");
            if(StringUtils.isEmpty(token)) {
                throw new ServiceException(Constants.TOKEN_IS_NULL);
            }
            DecodedJWT verify = JWTUtils.verify(token);
            if(verify == null) {
                throw new ServiceException(Constants.TOKEN_ERROR);
            }
//            if(!redisUtil.hasKey(token)) {
//                throw new ServiceException(Constants.TOKEN_INVALID);
//            }
            return true;
        }catch (Exception e){
            throw new ServiceException(Constants.TOKEN_ERROR);
        }
    }

}
